package com.atguigu.gmall.product.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
public class LoggingAspect {
    //声明切入点表达式
    @Pointcut(value = "execution(* com.atguigu.gmall.product.service.Calculator.*(..))")
    public void pointCut(){}

    //前置通知
    @Before("pointCut()") //引用切入点表达式
    public void beforeAdvice(JoinPoint joinPoint) {
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();
        System.out.println("Logging: The method "+methodName+" begins with "+ Arrays.toString(args));
    }

    //后置通知
    @After("pointCut()")
    public void afterAdvice(JoinPoint joinPoint) {
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logging: The method "+methodName+" ends");
    }

    //返回通知
    @AfterReturning(pointcut = "execution(* com.atguigu.gmall.product.service.Calculator.*(int , int ))",returning = "result")
    public void returningAdvice(JoinPoint joinPoint , Object result){
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();
        System.out.println("Logging: The method "+methodName+" returns "+result);
    }

    //异常通知
    @AfterThrowing(pointcut = "execution(* com.atguigu.gmall.product.service.Calculator.*(..))",throwing = "e")
    public void throwingAdvice(JoinPoint joinPoint,Throwable e){
        //获取方法名
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logging: The method "+methodName+" occurs "+e);
    }

    //环绕通知
    @Around("execution(* com.atguigu.gmall.product.service.Calculator.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
        //获取方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        //获取参数
        Object[] args = proceedingJoinPoint.getArgs();
        Object result=null;
        try {
            //前置通知
            System.out.println("★Logging: The method "+methodName+" begins with "+ Arrays.toString(args));
            //执行目标方法
            result = proceedingJoinPoint.proceed();
            //返回通知
            System.out.println("★Logging: The method "+methodName+" returns "+result);
        } catch (Throwable throwable) {
            //异常通知
            System.out.println("★Logging: The method "+methodName+" occurs "+throwable);
            throwable.printStackTrace();
        }finally {
            //后置通知
            System.out.println("★Logging: The method "+methodName+" ends");
        }
        return result;
    }


}
